<?php

namespace App\Listeners;

use App\Events\OrderAdjustments;
use App\Models\Adjustments;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class OrderAdjustmentsListen
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * 添加订单明细记录 （优惠券，运费啥的）
     *
     * @param  OrderAdjustments  $event
     * @return void
     */
    public function handle(OrderAdjustments $event)
    {
        $order = $event->order;
        $items = $order->items()->get();
        // 优惠券
        if($event->couponPrice != 0) {

            $price = bcdiv($event->couponPrice, $items->count(),2);

            foreach ($order->items as $item) {
                $data = [
                    'order_id' => $item->order_id,
                    'order_item_id' => $item->id,
                    'type' => 'discount',
                    'label' => '优惠券抵扣',
                    'included' => true,
                    'origin_code' => $order->coupon_id,
                    'amount' => $price,
                ];
                Adjustments::create($data);
            }
        }
        // 运费
        if ($order->freight_price > 0) {
            Adjustments::create([
                'order_id' => $order->id,
                'order_item_id' => 0,
                'type' => 'freight',
                'label' => '运费增加',
                'included' => true,
                'origin_code' => '',
                'amount' => $order->freight_price,
            ]);
        }
    }
}
